using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.OleDb;
using System.Runtime.InteropServices;
using System.IO;

namespace FingerReader_demo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        int fpcHandle;
        bool isConnected,one_to_one;
        int fingerid = 0;
        int fingerindex = 0;
        private OleDbConnection conn = null;
        private OleDbCommand cmd = null;
        private OleDbDataReader reader = null;
        [DllImport(@"C:\WINDOWS\system32\match.dll")]
        public static extern bool process(string ARegTemplate, string AVerTemplate);
        [DllImport(@"C:\WINDOWS\system32\match.dll")]
        public static extern int process10(string ARegTemplate, string AVerTemplate);

        private void btnInitialSensor_Click(object sender, EventArgs e) //初始化指纹仪
        {
            switch (comboBox1.Text)
            {
                case "9":axZKFPEngX1.FPEngineVersion="9";break;
                case"10":axZKFPEngX1.FPEngineVersion="10";break;
                default: axZKFPEngX1.FPEngineVersion = "9"; break;
            }
            //axZKFPEngX1.SetImageDirection(true);    //指纹图像做镜像翻转
            axZKFPEngX1.SensorIndex = 0;
            axZKFPEngX1.EnrollCount =int.Parse( comboBox2.Text);
            if (axZKFPEngX1.InitEngine() == 0)
            {
                fpcHandle = axZKFPEngX1.CreateFPCacheDB();
                statusBar1.Panels[1].Text = "Sensor Connected!";

                txtb1.Text = axZKFPEngX1.SensorCount.ToString();
                txtb2.Text = axZKFPEngX1.SensorIndex.ToString();
                txtb3.Text = axZKFPEngX1.ImageWidth.ToString();
                txtb4.Text = axZKFPEngX1.ImageHeight.ToString();
                txtb5.Text = axZKFPEngX1.SensorSN;
                isConnected = true;
                btnCloseSensor.Enabled = true;
                btnInitialSensor.Enabled = false;
                statusBar1.Panels[1].Text = "初始化成功!";
            }
            else
            {
                statusBar1.Panels[1].Text = "初始化失败!";
                isConnected = false;
            }
        }

        private void axZKFPEngX1_OnImageReceived(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnImageReceivedEvent e)
        {
            Graphics g = pictureBox1.CreateGraphics();
            Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            g = Graphics.FromImage(bmp);
            int handle1 = g.GetHdc().ToInt32();
            axZKFPEngX1.PrintImageAt(handle1, 0, 0, bmp.Width, bmp.Height);
            g.Dispose();
            pictureBox1.Image = bmp;
        }

        private void btnCloseSensor_Click(object sender, EventArgs e)//关闭指纹仪
        {
            axZKFPEngX1.EndEngine();
            btnCloseSensor.Enabled = false;
            btnInitialSensor.Enabled = true;
            isConnected = false;
        }

        private void axZKFPEngX1_OnFeatureInfo(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnFeatureInfoEvent e)
        {
            string strTemp = "指纹质量";
            if (e.aQuality == 0)
            {
                strTemp = strTemp + "合格";
            }
            else
            {
                if (e.aQuality == 1)
                {
                    strTemp = strTemp + "特征点不够";
                }
                else
                    strTemp = strTemp + "不合格";
            }
            if (axZKFPEngX1.IsRegister)
                if (axZKFPEngX1.EnrollIndex != 1)
                    strTemp = strTemp + "\r\n登记状态：请再按 " + (axZKFPEngX1.EnrollIndex - 1).ToString() + "次指纹";
                else
                    strTemp = strTemp + "\r\n登记状态：登记成功";
            statusBar1.Panels[2].Text = strTemp;
        }

        private void btn_register_Click(object sender, EventArgs e)//登记指纹
        {
            
            if (txt_fingerid.Text == "")
            {
                MessageBox.Show("请输入指纹编号");
                return;
            }
            try
            {
                fingerid = int.Parse(txt_fingerid.Text);
            }
            catch (Exception zxz)
            {
                MessageBox.Show("指纹编号必须为整形", "错误");
                return;
            }
            switch (cmb_fingerindex.Text.Trim())
            {
                case "左手小拇指": fingerindex = 0; break;
                case "左手无名指": fingerindex = 1; break;
                case "左手中指": fingerindex = 2; break;
                case "左手食指": fingerindex = 3; break;
                case "左手大拇指": fingerindex = 4; break;
                case "右手大拇指": fingerindex = 5; break;
                case "右手食指": fingerindex = 6; break;
                case "右手中指": fingerindex = 7; break;
                case "右手无名指": fingerindex = 8; break;
                case "右手小拇指": fingerindex = 9; break;
                default: fingerindex = 0; break;
            }
            if (axZKFPEngX1.FPEngineVersion == "10")
            {
                cmd = new OleDbCommand("select template_10 from template where UserId=" + fingerid + " and fingerindex=" + fingerindex, conn);
            }
            else
            {
                cmd = new OleDbCommand("select template_9 from template where UserId=" + fingerid + " and fingerindex=" + fingerindex, conn);
            }
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                if (!(reader[0] is DBNull))
                {
                    MessageBox.Show("该手指已经登记过指纹,请选择其它手指", "提示");
                    return;
                }
            }
            conn.Close();
            if (isConnected)
            {
                if (axZKFPEngX1.IsRegister)
                {
                    axZKFPEngX1.CancelEnroll();
                }
                axZKFPEngX1.BeginEnroll();
            }
            else
            {
                MessageBox.Show("请先初始化指纹仪", "提示");
            }
            statusBar1.Panels[1].Text = "登记指纹,请放手指";
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string connstr = ConfigurationManager.ConnectionStrings["zxz"].ConnectionString;
            conn = new OleDbConnection(connstr);
        }

        private void axZKFPEngX1_OnEnroll(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnEnrollEvent e)
        {
            byte[] tmpbyte;
            string tmp = "";
            tmp = axZKFPEngX1.GetTemplateAsString();
            //tmpbyte = Convert.FromBase64String(tmp);
            tmpbyte = (byte[])e.aTemplate;
            if (chk_finger.Checked)
            {
                if (Check_Duplicate_finger(tmp))
                {
                    MessageBox.Show("该指纹已经存在，请登记其它手指", "提示");
                    return;
                }
            }
            add_regtmp_db(tmpbyte);
        }

        private void add_regtmp_db(byte[] tmp)   //将登记指纹插入到数据库
        {
            string tmpstr = Convert.ToBase64String(tmp);
            cmd = new OleDbCommand("select * from template where userid=@userid and fingerindex=@fingerindex", conn);
            ((OleDbParameter)cmd.Parameters.Add("@userid", OleDbType.Integer)).Value = fingerid;
            ((OleDbParameter)cmd.Parameters.Add("@fingerindex", OleDbType.Integer)).Value = fingerindex;
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                if (axZKFPEngX1.FPEngineVersion == "10")
                {
                    cmd = new OleDbCommand("update template set template_10=@template where userid=@userid and fingerindex=@fingerindex", conn);
                }
                else
                {
                    cmd = new OleDbCommand("update template set template_9=@template where userid=@userid and fingerindex=@fingerindex" , conn);
                }
                ((OleDbParameter)cmd.Parameters.Add("@template", OleDbType.BSTR)).Value = tmpstr;
                ((OleDbParameter)cmd.Parameters.Add("@userid", OleDbType.Integer)).Value = fingerid;
                ((OleDbParameter)cmd.Parameters.Add("@fingerindex", OleDbType.Integer)).Value = fingerindex;
            }
            else
            {
                if (axZKFPEngX1.FPEngineVersion == "10")
                {
                    cmd = new OleDbCommand("insert into template(userid,fingerindex,template_10) values(@userid,@fingerindex,@template)", conn);
                }
                else
                {
                    cmd = new OleDbCommand("insert into template(userid,fingerindex,template_9) values(@userid,@fingerindex,@template)", conn);
                }

                ((OleDbParameter)cmd.Parameters.Add("@userid", OleDbType.Integer)).Value = fingerid;
                ((OleDbParameter)cmd.Parameters.Add("@fingerindex", OleDbType.Integer)).Value = fingerindex;
                ((OleDbParameter)cmd.Parameters.Add("@template", OleDbType.BSTR)).Value = tmpstr;
            }
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception zxz)
            {
                MessageBox.Show(zxz.ToString(), "错误");
                conn.Close();
                return;
            }
            conn.Close();
            statusBar1.Panels[1].Text = "登记指纹成功,已保存至数据库";
        }

        private bool Check_Duplicate_finger(string tmp)// 验证重复指纹
        {
            byte[] regtmp;
            string regtmpstr = "";
            if (axZKFPEngX1.FPEngineVersion == "10")
            {
                cmd = new OleDbCommand("select template_10 from template", conn);
            }
            else
            {
                cmd = new OleDbCommand("select template_9 from template", conn);
            }
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                if (reader[0] is DBNull)
                {
                    continue;
                }
                regtmpstr = (string)reader[0];
                if (axZKFPEngX1.FPEngineVersion == "10")
                {
                    if (process10(regtmpstr, tmp) == 1)
                    {
                        conn.Close();
                        return true;
                    }
                }
                else
                {
                    if (process(regtmpstr, tmp))
                    {
                        conn.Close();
                        return true;
                    }
                }
            }
            conn.Close();
            return false;
        }

        private void axZKFPEngX1_OnCapture(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnCaptureEvent e)
        {
            if (one_to_one)
            {
                string tmp = axZKFPEngX1.GetTemplateAsString();
                Verify_finger_one_to_one(tmp);
            }
            else
            {
                Verify_finger_one_to_many(e.aTemplate);
            }
        }

        private void Verify_finger_one_to_one(string tmp)//1:1验证
        {
            byte[] regtmp;
            string regtmpstr = "";
            if (txt_verifyid.Text == "")
            {
                MessageBox.Show("请输入指纹登记号", "提示");
                return;
            }

            try
            {
                fingerid = int.Parse(txt_verifyid.Text);
            }
            catch (Exception zxz)
            {
                MessageBox.Show(zxz.ToString(), "提示");
                return;
            }
            if (axZKFPEngX1.FPEngineVersion == "10")
            {
                cmd = new OleDbCommand("select template_10 from template where userid=" + fingerid, conn);
            }
            else
            {
                cmd = new OleDbCommand("select template_9 from template where userid=" + fingerid, conn);
            }
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                if (reader[0] is DBNull)
                    continue;
                regtmpstr = (string)reader[0];
                if (axZKFPEngX1.FPEngineVersion == "10")
                {
                    if (process10(regtmpstr, tmp) == 1)
                    {
                        statusBar1.Panels[1].Text = "1:1验证通过";
                        statusBar1.Panels[2].Text = "登记号为" + fingerid.ToString();
                        conn.Close();
                        return;
                    }
                }
                else
                {
                    if (process(regtmpstr, tmp))
                    {
                        statusBar1.Panels[1].Text = "1:1验证通过";
                        statusBar1.Panels[2].Text = "登记号为" + fingerid.ToString();
                        conn.Close();
                        return;
                    }
                }
            }
            conn.Close();
            statusBar1.Panels[1].Text = "1:1验证失败";
        }

        private void Verify_finger_one_to_many(object tmp)//1:N验证
        {
            int score = 9;
            int processedFPNumber = 0;
            int id = axZKFPEngX1.IdentificationInFPCacheDB(fpcHandle, tmp, ref score, ref processedFPNumber);
            if (id > 0)
            {
                cmd = new OleDbCommand("select userid from template where autoid=" + id, conn);
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                conn.Open();
                reader = cmd.ExecuteReader();
                if (reader.Read())
                    id = (int)reader[0];
                statusBar1.Panels[1].Text = "1:N验证通过";
                statusBar1.Panels[2].Text = "登记号为" + id.ToString();
                return;
            }
            statusBar1.Panels[1].Text = "1:N验证失败";
        }

        private void btn_verifmany_Click(object sender, EventArgs e)
        {
            if (isConnected)
            {
                if (axZKFPEngX1.IsRegister)
                {
                    axZKFPEngX1.CancelEnroll();
                }
                axZKFPEngX1.BeginCapture();
                one_to_one = false;
            }
        }

        private void btn_verifysingle_Click(object sender, EventArgs e)
        {
            if (isConnected)
            {
                if (axZKFPEngX1.IsRegister)
                {
                    axZKFPEngX1.CancelEnroll();
                }
                axZKFPEngX1.BeginCapture();
                one_to_one = true;
            }
        }

        private void btn_add_tmp_to_cache_Click(object sender, EventArgs e)
        {
            if (!isConnected)
            {
                MessageBox.Show("请先连接指纹仪", "提示");
                return;
            }
            byte[] tmp;
            string tmpstr = "";
            int autoid = 0;
            if (fpcHandle > 0)
            {
                axZKFPEngX1.FreeFPCacheDB(fpcHandle);
            }
            fpcHandle= axZKFPEngX1.CreateFPCacheDB();
            if (axZKFPEngX1.FPEngineVersion == "10")
            {
                cmd = new OleDbCommand("select autoid,template_10 from template", conn);
            }
            else
            {
                cmd = new OleDbCommand("select autoid,template_9 from template", conn);
            }
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                if (reader[1] is DBNull)
                    continue;
                autoid = (int)reader[0];
                tmpstr = (string)reader[1];
                tmp = Convert.FromBase64String(tmpstr);
                axZKFPEngX1.AddRegTemplateToFPCacheDB(fpcHandle, autoid, tmp);
            }
            MessageBox.Show("加载指纹模板成功", "提示");
        }

        private void btn_viewfinger_Click(object sender, EventArgs e)
        {
            ViewTmp tmpmanage = new ViewTmp();
            tmpmanage.conn = conn;
            tmpmanage.Show();
        }

        private void btn_path_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog browser = new FolderBrowserDialog();
            if (browser.ShowDialog() == DialogResult.OK)
            {
                txt_path.Text = browser.SelectedPath;
            }
        }

        private void btn_saveimg_Click(object sender, EventArgs e)
        {
            if (File.Exists(txt_path.Text + txt_filename.Text + ".jpg"))
            {
                MessageBox.Show("文件已存在", "提示");
                return;
            }
            axZKFPEngX1.SaveJPG(txt_path.Text+txt_filename.Text+".jpg");
        }

        private void btn_ctrLED_Click(object sender, EventArgs e)
        {
            axZKFPEngX1.ControlSensor(12, 1);//控制红灯闪一次，蜂鸣器短鸣两声
        }

        private void btn_ctrLED_G_Click(object sender, EventArgs e)
        {
            axZKFPEngX1.ControlSensor(11, 1);//控制绿灯闪一次，蜂鸣器长鸣一声
        }

        private void btn_ctrBEEP_Click(object sender, EventArgs e)
        {
            axZKFPEngX1.ControlSensor(13, 1);//控制绿灯闪一次，蜂鸣器长鸣一声
        }

    }
}
